package com.niubility.controller;

import com.niubility.entity.Message;
import com.niubility.entity.Refleck;
import com.niubility.exception.CustomException;
import com.niubility.server.IMessageServer;
import com.niubility.server.IRefleckServer;
import com.niubility.server.IUserService;
import com.niubility.vo.GetDate;
import com.niubility.vo.LoadandPage;
import com.niubility.vo.RefleckLoad;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * @ClassName: Refleckcontroller
 * @Description: 与前端交互，实现对反馈表的操作
 * @author: 张家乐
 * @DATE: 2018/1/31
 */

@RestController
@Transactional
public class RefleckController {
    @Resource
    private IRefleckServer refleckServer;
    @Resource
    private IMessageServer messageServer;
    @Resource
    private IUserService userService;

    Logger logger=Logger.getLogger(RefleckController.class);

    /**
     * @Description: 查询所有反馈信息反馈到pc端
     */
    @RequestMapping("/RefleckLoadAll")
    public void loadAllHander(HttpServletRequest request,HttpServletResponse response) throws CustomException {
        response.setCharacterEncoding("utf-8");
        String callBack="Refleck"; //设置初始值
        int page=0,turn=0;
        boolean b=false;
        try { //防止传出参数有误
            callBack=request.getParameter("callBack");
            page=Integer.parseInt(request.getParameter("page"));
            turn=Integer.parseInt(request.getParameter("turn"));
            b=true;
        }catch (Exception e){
            logger.debug("传入参数有误");
        }
        int displayCount=10;
        int maxpage=0;
        LoadandPage<RefleckLoad> loadandPage=new LoadandPage<RefleckLoad>();
        try{
            if(b){
                maxpage=refleckServer.LoadCount()/displayCount;
                //int k=10/0;
                page+=turn;
                page=page>maxpage+1?1:page<1?maxpage+1:page; //对翻页进行判断
                loadandPage.setPage(page);
                page=(page-1)*displayCount;
                List<RefleckLoad> refleckLoadList= refleckServer.LoadAll(page,displayCount);
                loadandPage.setList(refleckLoadList);
            }
        }catch (Exception ex){
            try {
                response.getWriter().write(callBack+"("+"{\"state\":"+0+"})");
            } catch (IOException e1) {
                logger.debug("response异常"+e1);
            }
            throw new CustomException();
        }

        String result=callBack+"("+ JSONObject.fromObject(loadandPage).toString()+")";
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            logger.debug("response异常"+e);
        }
    }

    /**
     * @Description: 修改反馈信息读取状态（未读变已读）并刷新读取按钮
     */
    @RequestMapping("/RefleckUpdateMark")
    @ResponseBody
    public void updateMark(HttpServletRequest request,HttpServletResponse response) throws CustomException {
        String callBack="Refleck"; //设置初始值
        int id=0; //反馈信息id
        int adminid=0; //当前管理员id
        boolean b=false;
        try {
            callBack=request.getParameter("callBack");
            id=Integer.parseInt(request.getParameter("reId"));
            adminid=Integer.parseInt(request.getParameter("adminId"));
            b=true;
        }catch (Exception e){
            logger.debug("获取前端参数异常");
        }
        String result;
        int i=0;
        try{
            if(b){
                i=refleckServer.UpdateMark(id);
                if(i==1){
                    Message message = new Message();
                    message.setMesSendid(adminid);
                    message.setMesMainid(refleckServer.LoadIdById(id)); //反馈信息填写人
                    message.setMesAssessmark(0);
                    message.setMesText("已读取您的反馈信息");
                    message.setMesDate(GetDate.getDate());
                    //事务加不上
                    //添加消息 通过发送者id 发送内容  发送消息时间
                    messageServer.MessageInsert(message);
                    //更改接收者的消息状态
                    userService.modifyUserMessageStatus(message.getMesMainid());

                }
            }
        }catch (Exception ex){
            try {
                response.getWriter().write(callBack+"("+"{\"state\":"+0+"})");
            } catch (IOException e1) {
                logger.debug("response异常"+e1);
            }
            throw new CustomException();
        }

        result=callBack+"("+"{\"state\":"+i+"})";
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            logger.debug("response异常"+e);
        }
    }
    /**
     * @Description: 删除反馈信息并刷新当前页面
     */
    @RequestMapping("/RefleckDeleteById")
    @ResponseBody
    public void deleteById(HttpServletRequest request,HttpServletResponse response){
        String callback="Refleck";
        int id=0,i=0;
        boolean b=false;
        try {
            callback=request.getParameter("callBack");
            id=Integer.parseInt(request.getParameter("reId"));
            b=true;
        }catch (Exception e){
            logger.debug("传入参数异常");
        }
        if(b){
            i=refleckServer.Delete(id);
        }
        String result=callback+"("+"{\"state\":"+i+"})";
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            logger.debug("response异常"+e);
        }
    }
    /**
     * @Description: 移动端用户提交反馈信息
     */
    @RequestMapping("/RefleckSaveById")
    @ResponseBody
    public void saveById(HttpServletRequest request,HttpServletResponse response){
        String callback="Refleck";
        Refleck refleck=new Refleck();
        int i=0;
        boolean b=false;
        try{
            callback=request.getParameter("callBack");
            refleck.setUsersId(Integer.parseInt(request.getParameter("usersId")));
            refleck.setReDate(GetDate.getDate());
            refleck.setReText(request.getParameter("reText"));
            b=true;

        }catch (Exception e){
            logger.debug("传入参数异常");
        }
        if(b){
            i=refleckServer.Save(refleck);
        }
        String result=callback+"("+"{\"state\":"+i+"})";
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            logger.debug("response异常"+e);
        }
    }

}
